from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.class_model import Class as ClassModel, ClassInDB
from app.schemas.class_schema import Class as ClassSchema, ClassCreate, ClassUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/classes", tags=["classes"])

@router.post("/create", response_model=APIResponse[ClassSchema])
def create_class(class_item: ClassCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating class with class_code: {class_item.class_code}")
    
    # 检查班级编码是否已存在
    db_class = db.query(ClassModel).filter(ClassModel.class_code == class_item.class_code).first()
    if db_class:
        logger.warning(f"Class already registered with class_code: {class_item.class_code}")
        return error_response(message="Class already registered", code=400)
    
    # 创建新班级
    db_class = ClassModel(
        class_code=class_item.class_code,
        class_name=class_item.class_name,
        academic_year_id=class_item.academic_year_id,
        grade=class_item.grade,
        class_no=class_item.class_no,
        classroom_id=class_item.classroom_id,
        head_teacher_id=class_item.head_teacher_id,
        student_count=class_item.student_count,
        status=class_item.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_class)
    db.commit()
    db.refresh(db_class)
    
    # 转换为Pydantic模型
    class_response = ClassInDB.model_validate(db_class)
    
    logger.info(f"Class created successfully with ID: {db_class.id}")
    return success_response(data=class_response, message="Class created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[ClassSchema]])
def read_classes(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching classes with skip: {skip}, limit: {limit}")
    
    classes = db.query(ClassModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    classes_response = [ClassInDB.model_validate(class_item) for class_item in classes]
    total = db.query(ClassModel).count()
    
    logger.info(f"Found {len(classes)} classes")
    return paginated_response(
        items=classes_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{class_id}", response_model=APIResponse[ClassSchema])
def read_class(class_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching class with ID: {class_id}")
    
    db_class = db.query(ClassModel).filter(ClassModel.id == class_id).first()
    if db_class is None:
        logger.warning(f"Class not found with ID: {class_id}")
        return error_response(message="Class not found", code=404)
    
    # 转换为Pydantic模型
    class_response = ClassInDB.model_validate(db_class)
    
    logger.info(f"Class found with ID: {class_id}")
    return success_response(data=class_response)

@router.put("/{class_id}", response_model=APIResponse[ClassSchema])
def update_class(class_id: int, class_item: ClassUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating class with ID: {class_id}")
    
    db_class = db.query(ClassModel).filter(ClassModel.id == class_id).first()
    if db_class is None:
        logger.warning(f"Class not found with ID: {class_id}")
        return error_response(message="Class not found", code=404)
    
    # 更新班级信息
    update_data = class_item.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_class, key, value)
    
    db_class.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_class)
    
    # 转换为Pydantic模型
    class_response = ClassInDB.model_validate(db_class)
    
    logger.info(f"Class updated successfully with ID: {class_id}")
    return success_response(data=class_response, message="Class updated successfully")

@router.delete("/{class_id}", response_model=APIResponse[None])
def delete_class(class_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting class with ID: {class_id}")
    
    db_class = db.query(ClassModel).filter(ClassModel.id == class_id).first()
    if db_class is None:
        logger.warning(f"Class not found with ID: {class_id}")
        return error_response(message="Class not found", code=404)
    
    db.delete(db_class)
    db.commit()
    
    logger.info(f"Class deleted successfully with ID: {class_id}")
    return success_response(message="Class deleted successfully")
